package alayse

import (
	"log"
	"fmt"
)

type decode interface {
	Alayse(data []byte) map[string][]byte;
}

type PngDecode struct{
	decode
}

var top8 = []int{137, 80, 78, 71, 13, 10, 26, 10};

var body = map[string][]byte{
	"IHDR":{73, 72, 68, 82},
}


func (PngDecode) Alayse(data []byte) map[string][]byte  {
	var dataMap = make(map[string][]byte);
	i:=0;
	for ; i<8; i++{
		if int(data[i]) != top8[i]{
			log.Print("该文件不是png格式的文件")
			return nil;
		}
	}
	for ; i<len(data); {
		var length int;
		var codeType string;
		length, i = getLength(data, i);
		codeType, i = getTypeCode(data, i);
		var request []byte;
		if length > 0 {
			request, i = getData(data, i, length);
		}
		_, i = getCRC(data, i);
		fmt.Printf("code Type:%s, length:%d, data:%v \n", codeType, len(request), request);
		dataMap[codeType] = request;
	}
	return dataMap;
}

func getLength(data []byte, beginIndex int) (int, int){
	return int(data[beginIndex])*256*256*256+int(data[beginIndex+1])*256*256+int(data[beginIndex+2])*256+int(data[beginIndex+3]), beginIndex+4;
}
func getTypeCode(data []byte, beginIndex int) (string, int){
	return string(data[beginIndex])+string(data[beginIndex+1])+string(data[beginIndex+2])+string(data[beginIndex+3]), beginIndex+4;
}

func getData(data []byte, beginIndex int, length int) ([]byte, int) {
	return data[beginIndex:beginIndex+length], beginIndex+length;
}

func getCRC(data []byte, beginIndex int) ([]byte, int) {
	return data[beginIndex:beginIndex+4], beginIndex+4;
}